/*
 * 编译命令 g++ multiThreadDemo.cpp -I. -o multiThread.exe -DDEBUG -fexec-charset=GBK
 * 运行命令 .\multiThread.exe
 */
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <chrono>

class ThreadPool {
public:
    explicit ThreadPool(size_t numThreads) : stop(false), pendingTasks(0) {
        for (size_t i = 0; i < numThreads; ++i) {
            workers.emplace_back([this] { this->workerLoop(); });
        }
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            stop = true;
        }
        condition.notify_all();
        for (std::thread &worker : workers) {
            if (worker.joinable()) {
                worker.join();
            }
        }
    }

    template<class F>
    void addTask(F&& task) {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            ++pendingTasks;
            tasks.emplace(std::forward<F>(task));
        }
        condition.notify_one();
    }

    void waitForTasks() {
        std::unique_lock<std::mutex> lock(taskCounterMutex);
        taskCompletionCondition.wait(lock, [this] { return pendingTasks == 0; });
    }

private:
    void workerLoop() {
        while (true) {
            std::function<void()> task;

            {
                std::unique_lock<std::mutex> lock(queueMutex);
                condition.wait(lock, [this] { return stop || !tasks.empty(); });

                if (stop && tasks.empty())
                    return;

                task = std::move(tasks.front());
                tasks.pop();
            }

            task();

            {
                std::unique_lock<std::mutex> lock(taskCounterMutex);
                --pendingTasks;
            }
            taskCompletionCondition.notify_one();
        }
    }

    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;

    std::mutex queueMutex;
    std::condition_variable condition;
    std::atomic<bool> stop;

    std::atomic<int> pendingTasks;
    std::mutex taskCounterMutex;
    std::condition_variable taskCompletionCondition;
};

// 示例类，构造函数接收 id
class MyTaskHandler {
public:
    explicit MyTaskHandler(int id) : taskId(id) {}

    void execute() {
        std::cout << "Executing task ID: " << taskId
                  << " on thread: " << std::this_thread::get_id()
                  << ", object address: " << this
                  << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(500)); // 模拟耗时操作
    }

private:
    int taskId;
};

int main() {
    ThreadPool pool(4); // 创建4个工作线程

    // 添加10个任务到线程池
    for (int i = 1; i <= 10; ++i) {
        auto handler = std::make_shared<MyTaskHandler>(i);  // 构造时传入 i
        pool.addTask([handler]() {
            handler->execute();      // 调用成员函数
        });
    }

    std::cout << "All tasks added. Waiting for completion..." << std::endl;
    pool.waitForTasks();
    std::cout << "All tasks have been completed." << std::endl;

    return 0;
}